﻿using System;
using System.Diagnostics;
using System.Timers;
using System.Windows.Forms;
using Rerun.Services;

namespace Rerun {

    /// <summary>
    /// 
    /// </summary>
    public class Program : Form {
        private static System.Timers.Timer timer;
        private static ProcessService processService;

        /// <summary>
        /// 
        /// </summary>
        /// <param name="e"></param>
        protected override void OnLoad(EventArgs e) {
            this.ShowInTaskbar = false;
            this.Visible = false;

            base.OnLoad(e);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <exception cref="ApplicationException"></exception>
        private Program() {
            try {
                Process.GetCurrentProcess().PriorityClass = ProcessPriorityClass.BelowNormal;

                if(ConfigurationService.ProcessInfoList.Count == 0) {
                    LoggingService.WriteEventLogEntry("There is nothing listed for monitoring, Rerun cannot start", EventLogEntryType.Error);

                    return;
                }

                timer = new System.Timers.Timer();
                timer.Interval = ConfigurationService.Interval;
                timer.Elapsed += new ElapsedEventHandler(OnTimedEvent);
                timer.Enabled = true;

                processService = new ProcessService();
            } catch(Exception e) {
                throw new ApplicationException(string.Format("There was a problem trying to run Rerun: {0}", e.Message));
            }
        }

        /// <summary>
        /// 
        /// </summary>
        [STAThread]
        public static void Main() {
            try {
                Application.Run(new Program());
            } catch(Exception e) {
                LoggingService.WriteEventLogEntry(e.Message, EventLogEntryType.Error);
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="source"></param>
        /// <param name="e"></param>
        /// <exception cref="ApplicationException"></exception>
        private static void OnTimedEvent(object source, ElapsedEventArgs e) {
            try {
                processService.EvaluateProcesses();
                processService.NotifyUser();

                ConfigurationService.ResetJustStartedValues();
            } catch(Exception ex) {
                throw new ApplicationException(ex.Message);
            }
        }
    }
}